import React, {PureComponent} from "react";
import Topic from "./components/Topic";
import Recommend from "./components/Recommend";
import Writer from "./components/Writer"
import List from "./components/List";
import {connect} from "react-redux";
import {HomeWrapper, HomeLeft, HomeRight, BackTop} from "./style";
import {actionCreater} from "./store";

class Home extends PureComponent {

  handleSCrollTop() {
    window.scroll(0, 0);
  }

  render() {
    return (
      <HomeWrapper>
        <HomeLeft>
          <img className="banner-img"
               src="https://upload.jianshu.io/admin_banners/web_images/4991/f35f847410c2d919aee3f40701e6c2e8d234661e.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540"
               alt="banner"/>
          <Topic/>
          <List/>
        </HomeLeft>
        <HomeRight>
          <Recommend/>
          <Writer/>
        </HomeRight>
        {this.props.showScroll ? <BackTop onClick={this.handleSCrollTop}>回到顶部</BackTop> : null}
      </HomeWrapper>
    )
  }

  componentDidMount() {
    this.props.changeHomeData();
    this.bindEvents();
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.props.changeScroll)
  }

  bindEvents() {
    window.addEventListener("scroll", this.props.changeScroll)
  }
}

const mapState = (state) => ({
  showScroll: state.getIn(["home", "showScroll"])
})

const mapDispatch = (dispatch) => ({
  changeHomeData() {
    const action = actionCreater.getHomeInfo();
    dispatch(action)
  },
  changeScroll(event) {
    if (document.documentElement.scrollTop > 400) {
      dispatch(actionCreater.toggleTopShow(true))
    } else {
      dispatch(actionCreater.toggleTopShow(false))
    }
  }
})

export default connect(mapState, mapDispatch)(Home);
